package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;


/**
 * The type Category service.
 */
@RequiredArgsConstructor
@Service
public class CategoryServiceImpl implements CategoryService {

    private final CategoryMapper categoryMapper;

    private final DishMapper dishMapper;

    private final SetmealMapper setMealMapper;

    @Override
    public PageResult pageList(CategoryPageQueryDTO cpqDTO) {
        //分页设置
        PageHelper.startPage(cpqDTO.getPage(), cpqDTO.getPageSize());
        //条件查询
        List<Category> list = categoryMapper.selectList(cpqDTO);
        //得到数据
        Page<Category> categoryPage = (Page<Category>) list;
        PageResult pageResult = new PageResult();
        pageResult.setTotal(categoryPage.getTotal());
        pageResult.setRecords(categoryPage.getResult());
        return pageResult;
    }

    @Override
    public List<Category> list(Integer type) {

        return categoryMapper.selectListByType(type);
    }

    @Override
    public void removeById(Long id) {
        if (dishMapper.selectCountByCategoryId(id) > 0) {
            //该分类中有菜品,不可删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }
        if (setMealMapper.selectCountByCategoryId(id)>0){
            //该分类中有套餐,不可删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        //删除该分类
        categoryMapper.deleteById(id);
    }

    @Override
    public void increase(CategoryDTO categoryDTO) {
        //名称格式校验
        String name = addNameCheck(categoryDTO);
        //分类排序格式校验
        Integer sort = SortCheck(categoryDTO);
        //得到当前登录员工的id
        Long empId = BaseContext.getCurrentId();
        Category category = Category.builder()
                .name(name)
                .sort(sort)
                .type(categoryDTO.getType())
                .status(0)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .createUser(empId)
                .updateUser(empId)
                .build();
        BaseContext.removeCurrentId();
        categoryMapper.insert(category);
    }

    @Override
    public void status(Long id, Integer status) {
        //更新状态
        Category category = Category.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        BaseContext.removeCurrentId();
        categoryMapper.updateStatusById(category);
    }

    @Override
    public void update(CategoryDTO categoryDTO) {
        //名称格式校验
        String name = updateNameCheck(categoryDTO);
        //分类排序格式校验
        Integer sort = SortCheck(categoryDTO);
        Long empId = BaseContext.getCurrentId();
        Category category = Category.builder()
                .id(categoryDTO.getId())
                .name(name)
                .sort(sort)
                .type(categoryDTO.getType())
                .updateTime(LocalDateTime.now())
                .updateUser(empId)
                .build();
        BaseContext.removeCurrentId();
        categoryMapper.update(category);
    }

    /**
     * 分类排序格式校验
     */
    private int SortCheck(CategoryDTO categoryDTO) {
        String sortDTO = categoryDTO.getSort();
        if (Objects.isNull(sortDTO)) throw new BaseException(MessageConstant.SORT_IS_NULL);
        if (!sortDTO.matches("-?\\d+")) throw new BaseException(MessageConstant.SORTING_MUST_BE_OF_INTEGER_TYPE);
        int sort = Integer.parseInt(sortDTO);
        if (sort < 0 || sort > 99) throw new BaseException(MessageConstant.RANGE_MISMATCH);
        return sort;
    }

    /**
     * 添加分类名称格式校验
     */
    private String addNameCheck(CategoryDTO categoryDTO) {
        //基础校验
        String name = nameCheck(categoryDTO);
        //判断分类名称是否唯一
        Integer count = categoryMapper.selectCountByName(name);
        if (count > 0) throw new BaseException(MessageConstant.NAME_IS_EXISTS);
        return name;
    }

    /**
     * 修改分类名称格式校验
     */
    private String updateNameCheck(CategoryDTO categoryDTO) {
        //基础校验
        String name = nameCheck(categoryDTO);
        Long id = categoryDTO.getId();
        //非我判断分类名称是否唯一
        Integer count = categoryMapper.selectCountByNameAndId(name, id);
        if (count > 0) throw new BaseException(MessageConstant.NAME_IS_EXISTS);
        return name;
    }

    /**
     * 分类名称格式校验
     */
    private String nameCheck(CategoryDTO categoryDTO) {
        String name = categoryDTO.getName();
        if (Objects.isNull(name)) throw new BaseException(MessageConstant.ILLEGAL_DISH_NAME);
        if (name.length() < 2 || name.length() > 20)
            throw new BaseException(MessageConstant.CATEGORY_NAME_LENGTH_INPUT_DOES_NOT_MATCH);
        return name;
    }
}
